package com.lzj.controller;

import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.domain.proto.storage.DownloadByteArray;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lzj.config.FastDfsEnum;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author
 */
@Api(tags = "FastFfs接口測試")
@RestController
@RequestMapping("/api/fastdfs")
public class FileController {
    @Autowired
    private FastFileStorageClient fileStorageClient;
    /**
     * dfs服务器ip 默认端口为8888
     */

    @ResponseBody
    @ApiOperation(value = "上传文件接口",httpMethod = "POST")
    @PostMapping("/upload")
    public String uploadFile(@ApiParam("文件")MultipartFile file)throws IOException{
        StorePath storePath = fileStorageClient.uploadFile(file.getInputStream(), file.getSize(),
                FilenameUtils.getExtension(file.getOriginalFilename()), null);
        String path = FastDfsEnum.FASTDFS_HOST+storePath.getFullPath();
        return "上传成功 地址为："+path;
    }
    @ResponseBody
    @ApiOperation(value = "删除文件接口",httpMethod = "POST")
    @PostMapping("/delete")
    public void deleteFile(String fileUrl){
        if(StringUtils.isEmpty(fileUrl)){
            return;
        }
        try {
            StorePath storePath = StorePath.parseFromUrl(fileUrl);
            fileStorageClient.deleteFile(storePath.getGroup()
                    ,storePath.getPath());
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
    @ResponseBody
    @ApiOperation(value = "下载文件接口",httpMethod = "POST")
    @PostMapping("/download")
    public void downloadFile(String fileUrl, HttpServletRequest request, HttpServletResponse response)throws IOException {
    try {
        StorePath storePath = StorePath.parseFromUrl(fileUrl);
        byte[] bytes = fileStorageClient.downloadFile(storePath.getGroup(), storePath.getPath()
                , new DownloadByteArray());
        response.getOutputStream().write(bytes);
        FileUtil.writeBytes(bytes, FileUtil.file(storePath.getPath()));
    }catch (Exception e){
        return;
    }
    }
}
